package com.accessibleworlds.report;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.accessibleworlds.R;
import com.accessibleworlds.maps.MapPinpoint;
import com.accessibleworlds.user.Options;
import com.accessibleworlds.user.UserPage;
import com.accessibleworlds.util.Connections;
import com.accessibleworlds.util.SharedVariables;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class EditOldReports extends MapActivity{

	private MapView map;
	private MapController controller;
	private MyLocationOverlay compass;
	private List<Overlay> overlayList;

	private GeoPoint touchedPoint;

	private ArrayList<ReportInformation> allReports;
	private ArrayList<ReportInformation> nearbyReports;
	private List<HashMap<String,String>> clickedNearbyReports;
	private HashMap<String,String> nearbyReportsValues;

	private ListView nearbyReportsListView;

	private Drawable star,blackstar,hole,noWheelchair,nopedestrian,noelevator,yellowhole,orangehole,redhole,yellowWheel,orangeWheel,redWheel;

	private MapPinpoint pinpoint,location,
	holeReportPoints,noPedestrianRoadReportPoints,noelevatorReportPoints,noWheelchairRampReportPoints,yellowholeReportPoints,orangeholeReportPoints,redholeReportPoints,yellowWheelReportPoints, orangeWheelReportPoints,redWheelReportPoints;
	
	private ProgressDialog progressDialog;

	private Dialog alertDialog;

	private final int ID_MENU_Search = 5, ID_MENU_Current = 4, ID_MENU_List = 3;
	private Geocoder geoCoder;
	private GeoPoint p;

	private double latitude= 0,longitude= 0;

	private LocationManager mlocManager;

	private LocationListener mlocListener;

	private String userID;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editoldreports);

		initializeVariables();
		changeLanguage();

		new GetReportsTask().execute();
	}

	@Override
	protected void onResume() {
		super.onResume();
		compass.enableCompass();
		changeLanguage();
	}

	@Override
	protected void onPause() {
		super.onPause();
		compass.disableCompass();
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this,UserPage.class);
		Bundle bundle = new Bundle();
		bundle.putString("previousID", SharedVariables.searchReportID);
		intent.putExtras(bundle);
		startActivity(intent);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		finish();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private void initializeVariables() {
		map = (MapView) findViewById(R.id.editReportMap);
		map.setBuiltInZoomControls(true);

		SearchReportOverlay searchReportOverlay = new SearchReportOverlay();
		overlayList = map.getOverlays();
		overlayList.add(searchReportOverlay);

		compass = new MyLocationOverlay(EditOldReports.this, map);
		overlayList.add(compass);

		controller = map.getController();

		GeoPoint point = new GeoPoint(41086147, 29048055);
		controller.animateTo(point);
		controller.setZoom(16);

		star = getResources().getDrawable(R.drawable.yellow_star);
		nopedestrian = getResources().getDrawable(R.drawable.nopedestrian);
		hole = getResources().getDrawable(R.drawable.hole);
		yellowhole= getResources().getDrawable(R.drawable.yellowhole);
		orangehole= getResources().getDrawable(R.drawable.orangehole);
		redhole= getResources().getDrawable(R.drawable.redhole);
		noWheelchair = getResources().getDrawable(R.drawable.nowheelchair);
		yellowWheel= getResources().getDrawable(R.drawable.yellowwheel);
		orangeWheel = getResources().getDrawable(R.drawable.orangewheel);
		redWheel = getResources().getDrawable(R.drawable.redwheel);
		noelevator = getResources().getDrawable(R.drawable.noelevator);
		blackstar = getResources().getDrawable(R.drawable.black_star);

		//hole is a violation type that corresponds to holes in a street or road
		holeReportPoints = new MapPinpoint(hole);
		overlayList.add(holeReportPoints);

		//yellow hole is a violation type which is a hole with normal status 
		yellowholeReportPoints = new MapPinpoint(yellowhole);
		overlayList.add(yellowholeReportPoints);

		//orange hole is a violation type which is a hole with minor status 
		orangeholeReportPoints = new MapPinpoint(orangehole);
		overlayList.add(orangeholeReportPoints);

		//red hole is a violation type which is a hole with urgent status 
		redholeReportPoints = new MapPinpoint(redhole);
		overlayList.add(redholeReportPoints);

		//noPedestrianRoad is a violation type that is related to pedestrian road problems
		noPedestrianRoadReportPoints = new MapPinpoint(nopedestrian);
		overlayList.add(noPedestrianRoadReportPoints);

		//noWheelchairRamp is a violation type that corresponds to unsuitable places for people with Wheel-chair
		noWheelchairRampReportPoints = new MapPinpoint(noWheelchair);
		overlayList.add(noWheelchairRampReportPoints);

		//yellow Wheel is a violation type which is a noWheelchairRamp with normal status
		yellowWheelReportPoints = new MapPinpoint(yellowWheel);
		overlayList.add(yellowWheelReportPoints);

		//orange Wheel is a violation type which is a noWheelchairRamp with minor status
		orangeWheelReportPoints = new MapPinpoint(orangeWheel);
		overlayList.add(orangeWheelReportPoints);

		//red Wheel is a violation type which is a noWheelchairRamp with urgent status
		redWheelReportPoints = new MapPinpoint(redWheel);
		overlayList.add(redWheelReportPoints);

		noelevatorReportPoints = new MapPinpoint(noelevator);
		overlayList.add(noelevatorReportPoints);

		pinpoint = new MapPinpoint(star);
		overlayList.add(pinpoint);

		location= new MapPinpoint(blackstar);
		overlayList.add(location);


		/* Use the LocationManager class to obtain GPS locations */
		mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		String bestProvider = mlocManager.getBestProvider(criteria, false);
		
		Location myLocation = mlocManager.getLastKnownLocation(bestProvider);
		if(location!=null) {
			latitude = myLocation.getLatitude();
			longitude = myLocation.getLongitude();
		}

		mlocListener = new MyLocationListener();
		mlocManager.requestLocationUpdates( bestProvider, 500, 1, mlocListener);
		
		SharedPreferences getPreferences = getSharedPreferences(SharedVariables.fileName, MODE_PRIVATE);
		userID = getPreferences.getString("userID", "");

		progressDialog = new ProgressDialog(EditOldReports.this);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
	}

	private void changeLanguage() {
		progressDialog.setMessage(getResources().getStringArray(R.array.loadingMessage)[SharedVariables.currentLanguage]);
	}

	/* Class My Location Listener */
	public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location loc) {
			latitude = loc.getLatitude();
			longitude = loc.getLongitude();
		}
		public void onProviderDisabled(String provider)	{
			Toast.makeText( getApplicationContext(), "Gps Disabled. Please turn it on to find your current location", Toast.LENGTH_SHORT ).show();
		}
		public void onProviderEnabled(String provider) {
			Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
			/* Use the LocationManager class to obtain GPS locations */
			mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

			mlocListener = new MyLocationListener();
			mlocManager.requestLocationUpdates( provider, 500, 1, mlocListener);

		}
		public void onStatusChanged(String provider, int status, Bundle extras)	{}
	}
	
	public class GetReportsTask extends AsyncTask<Void, Integer, String>{

		private String[] takenData = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected String doInBackground(Void... params) {

			if(Connections.serviceStatus()) {

				try {
					String url = Connections.URI+Connections.getOldReports;
					String [] parameters = {"accessCode","userID"};
					String [] paramaterValues = {SharedVariables.accessCode, userID};

					takenData = Connections.connection(url,parameters,paramaterValues);

					if("OK".equalsIgnoreCase(takenData[0])) {
						allReports = new ArrayList<ReportInformation>();
						for(int i=1;i<takenData.length;i++){
							JSONArray token = new JSONArray(takenData[i]);
							allReports.add(new ReportInformation(Integer.parseInt(token.getString(0)),
									token.getString(1),Integer.parseInt(token.getString(2)),
									token.getString(3),token.getString(4),
									Integer.parseInt(token.getString(5)), Integer.parseInt(token.getString(6)), Integer.parseInt(token.getString(7))));
						}
						publishProgress(1);
						return "OK";
					}
					else {
						publishProgress(2);
					}
				}
				catch (Exception ex) {
					publishProgress(2);
				}
			}
			else {
				publishProgress(0);
			}
			return "Fail";
		}

		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				progressDialog.dismiss();
				AlertDialog alertDialog = new AlertDialog.Builder(EditOldReports.this).create();
				alertDialog.setTitle(getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage]);
				alertDialog.setMessage(getResources().getStringArray(R.array.connectionProblemException)[SharedVariables.currentLanguage]);
				alertDialog.setButton(getResources().getStringArray(R.array.tryAgain)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						new GetReportsTask().execute();
					}
				});
				alertDialog.setButton2(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
				alertDialog.show();
			}
			else if(progress[0]==1) {
				progressDialog.dismiss();
				for(int i=0;i<allReports.size();i++){
					ReportInformation reportInformation = allReports.get(i);
					GeoPoint previousPoints = new GeoPoint(reportInformation.latitude, reportInformation.longitude);
					OverlayItem overlayItem = new OverlayItem(previousPoints, "CreateReport", "addedPoint");
					if(allReports.get(i).type == 1) {
						if(allReports.get(i).status.equals("normal"))
							yellowholeReportPoints.insertOverlayItem(overlayItem);
						else if(allReports.get(i).status.equals("minor"))
							orangeholeReportPoints.insertOverlayItem(overlayItem);
						else if(allReports.get(i).status.equals("urgent"))
							redholeReportPoints.insertOverlayItem(overlayItem);
						else
							holeReportPoints.insertOverlayItem(overlayItem);
					}
					else if(allReports.get(i).type == 2) {
						noPedestrianRoadReportPoints.insertOverlayItem(overlayItem);
					}
					else if(allReports.get(i).type == 3) {
						if(allReports.get(i).status.equals("normal"))
							yellowWheelReportPoints.insertOverlayItem(overlayItem);
						else if(allReports.get(i).status.equals("minor"))
							orangeWheelReportPoints.insertOverlayItem(overlayItem);
						else if(allReports.get(i).status.equals("urgent"))
							redWheelReportPoints.insertOverlayItem(overlayItem);
						else
							noWheelchairRampReportPoints.insertOverlayItem(overlayItem);
					}
					else if(allReports.get(i).type == 4) {
						noelevatorReportPoints.insertOverlayItem(overlayItem);
					}
					else 
						holeReportPoints.insertOverlayItem(overlayItem);
				}
				map.postInvalidate();
			}
			else if(progress[0]==2) {
				progressDialog.dismiss();
				Toast.makeText(EditOldReports.this, getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage], Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected void onPostExecute(String result) {}
	}

	private class SearchReportOverlay extends Overlay {

		private long startTime;
		private long finishTime;

		@Override
		public boolean onTouchEvent(MotionEvent e, MapView mapView) {
			if(e.getAction()==MotionEvent.ACTION_DOWN) {
				startTime = System.currentTimeMillis();
				touchedPoint = map.getProjection().fromPixels((int) e.getX(), (int) e.getY());
				if(pinpoint.size()>0) {
					pinpoint.removeOverlayItem(0);
				}
				OverlayItem overlayItem = new OverlayItem(touchedPoint, "searchReport", "touchedPoint");
				pinpoint.insertOverlayItem(overlayItem);
			}
			if(e.getAction()==MotionEvent.ACTION_UP) {
				finishTime = System.currentTimeMillis();
				if(finishTime - startTime >= 1000) {
					//Get nearby reports
					Location touchedLocation = new Location("touchedPoint");
					touchedLocation.setLatitude(touchedPoint.getLatitudeE6()/1e6);
					touchedLocation.setLongitude(touchedPoint.getLongitudeE6()/1e6);

					nearbyReports = new ArrayList<ReportInformation>();

					/*Zoom levels vary from 1 to 20. 20 is the largest zoom level therefore u can only zoom upto that point
					 *Scale starts with 591657550.500000 and with each zoom it is divided by 2. 20'th value is 1128.497220
					 * By dividing it to 100 in practical we can search a 11 m radius at the full zoom and 5916km at no zoom
					 */
					double precision = 1183315100.95872/Math.pow(2,map.getZoomLevel());
					precision /= 100;
					clickedNearbyReports = new ArrayList<HashMap<String,String>>();
					for(int i=0;i<allReports.size();i++){
						Location nearLocation = new Location("reportLocation");

						ReportInformation token = allReports.get(i);
						nearLocation.setLatitude(token.latitude/1e6);
						nearLocation.setLongitude(token.longitude/1e6);
						System.out.println(precision);
						if(touchedLocation.distanceTo(nearLocation)<=precision){
							nearbyReports.add(token);
							nearbyReportsValues = new HashMap<String, String>();
							if(allReports.get(i).type == 1) {
								if(allReports.get(i).status.equals("normal"))
									nearbyReportsValues.put("image", Integer.toString(R.drawable.yellowhole));
								else if(allReports.get(i).status.equals("minor"))
									nearbyReportsValues.put("image", Integer.toString(R.drawable.orangehole));
								else if(allReports.get(i).status.equals("urgent"))
									nearbyReportsValues.put("image", Integer.toString(R.drawable.redhole));
								else
									nearbyReportsValues.put("image", Integer.toString(R.drawable.hole));
							}
							else if(allReports.get(i).type == 2) {
								nearbyReportsValues.put("image", Integer.toString(R.drawable.nopedestrian));
							}
							else if(allReports.get(i).type == 3) {
								if(allReports.get(i).status.equals("normal"))
									nearbyReportsValues.put("image", Integer.toString(R.drawable.yellowwheel));
								else if(allReports.get(i).status.equals("minor"))
									nearbyReportsValues.put("image", Integer.toString(R.drawable.orangewheel));
								else if(allReports.get(i).status.equals("urgent"))
									nearbyReportsValues.put("image", Integer.toString(R.drawable.redwheel));
								else
									nearbyReportsValues.put("image", Integer.toString(R.drawable.nowheelchair));
							}
							else if(allReports.get(i).type == 4) {
								nearbyReportsValues.put("image", Integer.toString(R.drawable.noelevator));
							}
							else 
								nearbyReportsValues.put("image", Integer.toString(R.drawable.hole));
							nearbyReportsValues.put("title", token.title);
							clickedNearbyReports.add(nearbyReportsValues);
						}
					}

					//Keys used in hashmap
					String[] map = {"image", "title"};
					//Titles of the xml
					int[] titles = {R.id.violationType, R.id.title};

					alertDialog = new Dialog(EditOldReports.this);
					if(nearbyReports.size()==0)
						alertDialog.setTitle("No Nearby Report");
					else
						alertDialog.setTitle("Nearby Reports");
					alertDialog.setContentView(R.layout.near_neighbor_list);
					nearbyReportsListView = (ListView) alertDialog.findViewById(R.id.nearList);
					SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), clickedNearbyReports, R.layout.nearby_reports_list, map, titles);
					nearbyReportsListView.setAdapter(adapter);
					nearbyReportsListView.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
							ReportInformation reportInformation = nearbyReports.get(position);
							Intent intent = new Intent(EditOldReports.this,ReportView.class);
							Bundle bundle = new Bundle();
							bundle.putString("previousID", SharedVariables.editOldReportsID);
							bundle.putString("reportID", ""+reportInformation.reportID);
							bundle.putString("status", reportInformation.status);
							bundle.putString("type", ""+reportInformation.type);
							bundle.putString("title", reportInformation.title);
							bundle.putString("description", reportInformation.description);
							bundle.putString("latitude", ""+reportInformation.latitude);
							bundle.putString("longitude", ""+reportInformation.longitude);
							bundle.putString("rate", ""+reportInformation.rate);
							intent.putExtras(bundle);
							startActivity(intent);
							overridePendingTransition(R.anim.fade, R.anim.hold);
							alertDialog.dismiss();
							finish();
						}
					});
					alertDialog.show();
				}
			}
			return super.onTouchEvent(e, mapView);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mainMenu = getMenuInflater();
		mainMenu.inflate(R.menu.mainmenu, menu);
		MenuItem item = menu.add(Menu.NONE, ID_MENU_Search, Menu.NONE, R.string.search);
		item.setShortcut('5', 'x');
		MenuItem item2 = menu.add(Menu.NONE, ID_MENU_Current, Menu.NONE, R.string.current);
		item2.setShortcut('4', 'c');
		MenuItem item3 = menu.add(Menu.NONE, ID_MENU_List, Menu.NONE, R.string.list);
		item3.setShortcut('3', 'v');
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		//menu.clear();
		menu.findItem((R.id.menuOptions)).setTitle(getResources().getStringArray(R.array.options)[SharedVariables.currentLanguage]);
		menu.findItem(R.id.menuOptions).setIcon(R.drawable.optionsicon);
		menu.findItem((R.id.menuExit)).setTitle(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage]);
		menu.findItem((R.id.menuExit)).setIcon(R.drawable.exiticon);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==R.id.menuOptions) {
			Intent intent = new Intent(this,Options.class);
			Bundle bundle = new Bundle();
			bundle.putString("previousID", SharedVariables.creatReportID);
			intent.putExtras(bundle);
			startActivity(intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
		}
		else if (item.getItemId()==R.id.menuExit) {
			finish();
		}
		else if (item.getItemId()== ID_MENU_Search){
			alertDialog = new Dialog(this);
			alertDialog.setContentView(R.layout.message_to_admin);
			alertDialog.setTitle("Search Location");
			final EditText Topic = (EditText) alertDialog.findViewById(R.id.mesToAdminTopic);
			Topic.setHint("Enter your city");
			final EditText Message = (EditText) alertDialog.findViewById(R.id.mesToAdminMessage);
			Message.setHint("Enter your location");
			Button loc = (Button) alertDialog.findViewById(R.id.mesToAdminButton);
			loc.setText("Find location");
			alertDialog.show();
			loc.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					alertDialog.dismiss();
					List<Address> addresses=null;
					geoCoder = new Geocoder(getApplicationContext());
					try {
						addresses = geoCoder.getFromLocationName(Message.getText().toString()+" "+Topic.getText().toString(),5);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(addresses.size());
					for(int i=0;i<addresses.size();i++)
						System.out.println(addresses.get(i));
					if(addresses.size() > 0)
					{
						p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6), 
								(int) (addresses.get(0).getLongitude() * 1E6));

						controller.animateTo(p);
						controller.setZoom(20);
						if(location.size()>0) {
							location.removeOverlayItem(0);
						}
						OverlayItem currentLocation = new OverlayItem(p, "Current Location", "snip");
						location.insertOverlayItem(currentLocation);
					}
					else
					{
						AlertDialog.Builder adb = new AlertDialog.Builder(EditOldReports.this);
						adb.setTitle("Google Map");
						adb.setMessage("Please Provide the Proper Place");
						adb.setPositiveButton("Close",null);
						adb.show();
					}
				}
			});
		}
		else if (item.getItemId()== ID_MENU_Current){
			if(latitude != 0 && longitude != 0){
				p = new GeoPoint( (int) (latitude * 1E6), 
						(int) (longitude * 1E6));

				controller.animateTo(p);
				controller.setZoom(20);
				if(location.size()>0) {
					location.removeOverlayItem(0);
				}
				OverlayItem currentLocation = new OverlayItem(p, "Current Location", "snip");
				location.insertOverlayItem(currentLocation);
			}
			else{
				AlertDialog.Builder adb = new AlertDialog.Builder(EditOldReports.this);
				adb.setTitle("Google Map");
				adb.setMessage("If your GPS is closed please turn on or please try again later");
				adb.setPositiveButton("Close",null);
				adb.show();
			}
		}
		else if(item.getItemId() == ID_MENU_List){
			clickedNearbyReports = new ArrayList<HashMap<String,String>>();
			nearbyReports = new ArrayList<ReportInformation>();
			System.out.println("size: "+allReports.size());
			for(int i=0;i<allReports.size();i++){
				Location nearLocation = new Location("reportLocation");
				ReportInformation token = allReports.get(i);
				System.out.println("lat-long :"+token.latitude+" "+token.longitude);
				nearLocation.setLatitude(token.latitude/1e6);
				nearLocation.setLongitude(token.longitude/1e6);
				nearbyReports.add(token);
				nearbyReportsValues = new HashMap<String, String>();
				if(allReports.get(i).type == 1) {
					if(allReports.get(i).status.equals("normal"))
						nearbyReportsValues.put("image", Integer.toString(R.drawable.yellowhole));
					else if(allReports.get(i).status.equals("minor"))
						nearbyReportsValues.put("image", Integer.toString(R.drawable.orangehole));
					else if(allReports.get(i).status.equals("urgent"))
						nearbyReportsValues.put("image", Integer.toString(R.drawable.redhole));
					else
						nearbyReportsValues.put("image", Integer.toString(R.drawable.hole));
				}
				else if(allReports.get(i).type == 2) {
					nearbyReportsValues.put("image", Integer.toString(R.drawable.nopedestrian));
				}
				else if(allReports.get(i).type == 3) {
					if(allReports.get(i).status.equals("normal"))
						nearbyReportsValues.put("image", Integer.toString(R.drawable.yellowwheel));
					else if(allReports.get(i).status.equals("minor"))
						nearbyReportsValues.put("image", Integer.toString(R.drawable.orangewheel));
					else if(allReports.get(i).status.equals("urgent"))
						nearbyReportsValues.put("image", Integer.toString(R.drawable.redwheel));
					else
						nearbyReportsValues.put("image", Integer.toString(R.drawable.nowheelchair));
				}
				else if(allReports.get(i).type == 4) {
					nearbyReportsValues.put("image", Integer.toString(R.drawable.noelevator));
				}
				else 
					nearbyReportsValues.put("image", Integer.toString(R.drawable.hole));
				nearbyReportsValues.put("title", token.title);
				clickedNearbyReports.add(nearbyReportsValues);
			}

			//Keys used in hashmap
			String[] map = {"image", "title"};
			//Titles of the xml
			int[] titles = {R.id.violationType, R.id.title};

			alertDialog = new Dialog(EditOldReports.this);
			if(nearbyReports.size()==0)
				alertDialog.setTitle("No Nearby Report");
			else
				alertDialog.setTitle("Nearby Reports");
			alertDialog.setContentView(R.layout.near_neighbor_list);
			nearbyReportsListView = (ListView) alertDialog.findViewById(R.id.nearList);
			SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), clickedNearbyReports, R.layout.nearby_reports_list, map, titles);
			nearbyReportsListView.setAdapter(adapter);
			nearbyReportsListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					ReportInformation reportInformation = nearbyReports.get(position);
					p = new GeoPoint( (int) (reportInformation.latitude), 
							(int) (reportInformation.longitude));

					controller.animateTo(p);
					controller.setZoom(20);
					alertDialog.dismiss();
				}
			});
			alertDialog.show();
		}
		return super.onOptionsItemSelected(item);

	}
}
